"ui";
toastLog("脚本版本:23.12.31");
ui.layout(
  <vertical padding="16">
    <card margin="3 1" cardElevation="0" cardCornerRadius="10" cardBackgroundColor="#AFEEEE" alpha="1">
      <linear gravity="left">
        <Switch
          id="autoService"
          Thumbcolor="#000000"
          Trackcolor="#000000"
          text="无障碍服务"
          textColor="#000000"
          w="150"
          checked="{{auto.service != null}}"
          padding="8 8 8 8"
          textSize="15sp"
        />
      </linear>
      <linear gravity="right">
        <Switch
          id="overlayService"
          Thumbcolor="#000000"
          Trackcolor="#000000"
          text="悬浮窗权限"
          textColor="#000000"
          w="150"
          checked="{{auto.service != null}}"
          padding="8 8 8 8"
          textSize="15sp"
        />
      </linear>
    </card>
    <text textSize="16sp" marginLeft="100" textColor="black" text="QQ群：798052476" />
    <text textSize="16sp" textColor="black" text="单选:" />
    <radiogroup>
      <radio id="radio1" text="自定义红包Bounds" />
      <radio id="radio2" text="抖音极速版" />
      <radio id="radio3" text="抖音火山版" />
      <radio id="radio4" text="指定房间打赏礼物" />
      <radio id="radio5" text="抖音最新版本" />
    </radiogroup>
    <text textSize="16sp" textColor="black" text="多选:" />
    <checkbox id="check1" text="互粉互赞的评论" />
    <checkbox id="check2" text="给主播点赞" />
    <checkbox id="check3" text="随机名人名言" />
    <checkbox id="check4" text="直播领金币(可能影响使用)" />
    <button id="btn" text="提交" bg="#00ff00" />
    <text textSize="16sp" textColor="#0000ff" text="玩法介绍：" marginTop="10" />
    <text textSize="16sp" textColor="#0000ff" text="1,自动打开单选app红包广场" />
    <text textSize="16sp" textColor="#0000ff" text="2,自动搜索红包控件，进入房间" />
    <text textSize="16sp" textColor="#0000ff" text="3,自动搜查询红包变最后10秒弹出，开始抢红包" />
    <text textSize="16sp" textColor="#0000ff" text="4,查询下一个红包，没有到广场循环任务" />
    <text textSize="16sp" textColor="#0000ff" text="5,连续10次没有抢红包清理app重新开始" />
    <text textSize="16sp" textColor="#0000ff" text="6,连续20次没有抢红包到退出脚本" />
    <text textSize="16sp" textColor="#0000ff" text="7,每天抖币和礼物合计：50" />
    <text textSize="16sp" textColor="red" text="注意:这脚本不要在同wifi下批量跑！！！" />
    <text textSize="16sp" textColor="red" text="注意:这脚本不要在同wifi下批量跑！！！" />
    <text textSize="16sp" textColor="red" text="注意:这脚本不要在同wifi下批量跑！！！" />
  </vertical>
);
let storage = storages.create("1934017003@qq.com-dy");
toastLog("5秒后自动运行");
threads.start(function () {
  sleep(5000);
  try {
    let 提交 = className("Button").text("提交").findOne(5000);
    if (提交) {
      提交.click();
    }
  } catch (error) {
    log(error);
  }
});
if (storage.get("任务-单选")) {
  let 单选 = storage.get("任务-单选");
  let 多选 = storage.get("任务-多选");
  if (单选 == "自定义红包Bounds") {
    ui.radio1.click();
  } else if (单选 == "抖音极速版") {
    ui.radio2.click();
  } else if (单选 == "抖音火山版") {
    ui.radio3.click();
  } else if (单选 == "抖音最新版本") {
    ui.radio5.click();
  } else if (单选 == "指定房间打赏礼物") {
    ui.radio4.click();
  }
  if (多选.length > 0) {
    多选.forEach((v) => {
      if (v == "互粉互赞的评论") {
        ui.check1.click();
      }
      if (v == "给主播点赞") {
        ui.check2.click();
      }
      if (v == "随机名人名言") {
        ui.check3.click();
      }
      if (v == "直播领金币(可能影响使用)") {
        ui.check4.click();
      }
    });
  }
} else {
  ui.radio3.click();
}
ui.btn.on("click", function () {
  var radioText = "";
  if (ui.radio1.isChecked()) radioText = ui.radio1.text;
  else if (ui.radio2.isChecked()) radioText = ui.radio2.text;
  else if (ui.radio3.isChecked()) radioText = ui.radio3.text;
  else if (ui.radio4.isChecked()) radioText = ui.radio4.text;
  else if (ui.radio5.isChecked()) radioText = ui.radio5.text;

  var checkText = [];
  if (ui.check1.isChecked()) checkText.push(ui.check1.text);
  if (ui.check2.isChecked()) checkText.push(ui.check2.text);
  if (ui.check3.isChecked()) checkText.push(ui.check3.text);
  if (ui.check4.isChecked()) checkText.push(ui.check4.text);
  storage.put("任务-单选", radioText);
  storage.put("任务-多选", checkText);
  toastLog("单选：" + radioText + "\n多选：" + checkText.join(", "));
  ui.finish();
  engines.execScript(radioText, "开始跑抖音();\n" + 开始跑抖音.toString());
  log(engines.all());
});

function 开始跑抖音() {
  let timeStart = new Date().getTime();
  setScreenMetrics(1080, 2400);
  var 查询红包次数 = 0; //用来记录一个直播房间查询红包次数 当达到次数退出直播间
  var 没抢到红包次数 = 0; //如果15次都没抢到就推出
  //通用工具========
  const height = device.height;
  const width = device.width;
  const width2 = width / 2;
  const height2 = height / 2;
  events.on("exit", function () {
    log("退出任务");
    log("本次抢到：" + 抢到红包统计 + "抖币");
    log("本次抢到：" + 抢到啤酒统计 + "啤酒");
    log("本次抢到：" + 抢到小爱心统计 + "小爱心");
    log("本次抢到：" + 抢到棒棒糖统计 + "棒棒糖");
    log("本次抢到：" + 抢到小皇冠统计 + "小皇冠");
    log("本次抢到：" + 抢到撩一下统计 + "撩一下");
    let endTime = new Date().getTime() - timeStart;
    console.show();
    console.error(
      "本次运行价值：" + (抢到红包统计 + 抢到啤酒统计 * 2 + 抢到小爱心统计 + 抢到棒棒糖统计 * 9 + 抢到小皇冠统计 * 20 + 抢到撩一下统计 * 19)
    );
    console.error("本次运行时间：" + endTime / 60000 + "分钟");
    sleep(3000);
    console.hide();
  });
  // threads.start(function () {
  //   events.setKeyInterceptionEnabled("volume_down", true);
  //   events.observeKey();
  //   events.onceKeyDown("volume_down", function () {
  //     log("音量按键点击，退出");
  //     exit();
  //   });
  // });
  let 抢到红包统计 = 0; //统计抢到的红包
  let 抢到啤酒统计 = 0;
  let 抢到小爱心统计 = 0;
  let 抢到小皇冠统计 = 0;
  let 抢到棒棒糖统计 = 0;
  let 抢到撩一下统计 = 0;
  let 互粉互赞 = [
    "互粉互赞，相亲相爱一家人，你点我来我点你，你赞我来我赞你，耶耶耶欧耶哈哈哈哈哈哈",
    "我们互关互赞，互相支持一下。",
    "互粉互赞当然是自愿的，但是你们所认为的这一个小小的自由，将会绝对地导致一些优秀作者的没落。",
    "我们互相点赞，互相评论，互相成为粉丝，让我们共同见证美好",
    "你可以先粉我，我也可以先粉你，然后咱们这个都是都是不会骗的，只要你粉了我，以后我就会粉你去",
    "你若投我以赞 我必报你以心❤️",
    "你赞我就赞 ，你关我回关 。",
    "祝愿我们大家的粉丝日益增多，互相努力，共同加油，争创佳绩",
    "互动，互粉，互赞你走我不留，你来不管刮风下雨我去接你",
  ];
  // 设置最低亮度 同时关闭自动亮度
  device.setBrightnessMode(0);
  // device.setBrightness(1);
  var username = "小宝贝"; //直播房间名称
  console.setPosition(0, height * 0.65);
  console.show();
  let 给主播点赞 = false;
  let 随机名人名言 = false;
  let 自动互粉互赞 = false;
  let 直播领金币 = false;
  let data_true = "snssdk1128://hotlive/feed"; //抖音
  let killname = "抖音";
  let storage = storages.create("1934017003@qq.com-dy");
  if (storage.get("任务-单选") == "自定义红包Bounds") {
    var ll = dialogs.rawInput("自定义抢红包bounds", "");
    if (ll != null) {
      let ss = ll.match(/\d+/g);
      let storage = storages.create("1934017003@qq.com-dy");
      storage.put("bounds1", ss[0] - 10);
      storage.put("bounds2", ss[1] - 10);
      storage.put("bounds3", Number(ss[2]) + 10);
      storage.put("bounds4", Number(ss[3]) + 10);
      log(storage.get("bounds1"));
      log(storage.get("bounds2"));
      log(storage.get("bounds3"));
      log(storage.get("bounds4"));
      toastLog("请重新运行");
      exit();
    }
  }
  let bounds1 = 380;
  let bounds2 = 1000;
  let bounds3 = 800;
  let bounds4 = 1500;

  if (storage.get("bounds1")) {
    bounds1 = storage.get("bounds1");
    bounds2 = storage.get("bounds2");
    bounds3 = storage.get("bounds3");
    bounds4 = storage.get("bounds4");
    log(bounds1);
  }
  if (storage.get("任务-单选")) {
    let 单选 = storage.get("任务-单选");
    let 多选 = storage.get("任务-多选");
    var 运行环境haimbot = false;
    try {
      var qq = require("/sdcard/脚本/QQ");
      qq.init();
      log(currentPackage());
      if (currentPackage() == "com.hamibot.hamibot") {
        运行环境haimbot = true;
      }
    } catch (error) {
      console.info("没有找到QQ,执行haimbot代码");
      运行环境haimbot = true;
    }
    if (单选 == "抖音极速版") {
      toastLog("需要抖音极速版版本：28.0.0");
      data_true = "snssdk2329://hotlive/feed"; //抖音极速版
      killname = "抖音极速版";
    } else if (单选 == "抖音火山版") {
      data_true = "snssdk8663://hotlive/feed"; //抖音火山版本
      killname = "抖音火山版";
    } else if (单选 == "指定房间打赏礼物") {
      到指定房间打赏();
    }
    if (多选.length > 0) {
      多选.forEach((v) => {
        if (v == "互粉互赞的评论") {
          自动互粉互赞 = true;
        }
        if (v == "给主播点赞") {
          给主播点赞 = true;
        }
        if (v == "随机名人名言") {
          随机名人名言 = true;
        }
        if (v == "直播领金币(可能影响使用)") {
          直播领金币 = true;
        }
      });
    }
  }
  let appid = getPackageName(killname);
  let 重新打开直播广场 = true;
  // threads.start(function () {
  //   findAndClick("允许|立即开始");
  // });
  // if (!requestScreenCapture()) {
  //   toast("请求截图失败");
  //   exit();
  // }
  while (true) {
    打开抖音();
    //查询直播广场红包按键
    sleep(5000);
    let tets = className("android.widget.ImageView").find();
    广场小红包(tets);
    if (重新打开直播广场) {
      continue;
    }
    let username2 = className("android.widget.TextView")
      .id(appid + ":id/user_name")
      .visibleToUser()
      .findOne(5000);

    if (username2 && username == username2.text()) {
      log(username2.text());
      console.error("2次直播房间名字一样,清理进程后重新启动");
      killApp(killname);
      continue;
    }
    if (username2) {
      log("直播间名称:《" + username2.text() + "》");
      username = username2.text();
    }
    findRedPacket();
    back();
    sleep(2000);
    back();
  }

  function 打开抖音() {
    launchApp(killname);
    sleep(3000);
    app.startActivity({
      data: data_true,
    });
  }

  function 广场小红包(tets) {
    log("当前页面控件：" + tets.length);
    for (let key = 0; key < tets.length; key++) {
      let widthNum = tets[key].bounds().right - tets[key].bounds().left;
      let heightNum = tets[key].bounds().bottom - tets[key].bounds().top;
      if (30 < heightNum && heightNum < 70 && 100 < widthNum && widthNum < 170) {
        tets[key].parent().parent().click();
        sleep(1000);
        重新打开直播广场 = false;
        break;
      }
      if (key == tets.length - 1) {
        console.verbose("页面没有红包，重新打开");
        重新打开直播广场 = true;
        break;
      }
    }
  }
  /**
   * 等待时间
   * @param {*} widgetOneRedPacket 父类对象
   */
  function timesplit(widgetOneRedPacket) {
    let is_time = "";
    if (widgetOneRedPacket) {
      is_time = widgetOneRedPacket.desc();
    } else {
      log("查询的数据对于错误");
      return false;
    }
    if (/分/.test(is_time)) {
      let descMountNum = is_time.replace(/[^\d|分]/g, "").split(/分/);
      if (descMountNum[0] > 2) {
        log("等待超过3分钟 不抢了");
        return false;
      }
      if (没抢到红包次数 == 10) {
        console.info("连续10次没抢到 清理缓存");
        killApp(killname);
        return false;
      }
      let timestampstart = new Date().getTime();
      log("等待:" + is_time);
      if (随机名人名言) {
        抖音复制上面评价();
      }
      if (自动互粉互赞) {
        抖音互粉互赞();
      }
      if (给主播点赞) {
        抖音给主播点赞();
      }
      if (直播领金币) {
        let 领 = widgetGetOne("领..", 8000);
        if (领) {
          clickCenter(领);
          findAndClick("开宝箱", 8000, 1000);
          sleep(2000);
          log("点击固定坐标");
          back();
          sleep(1000);
          back();
        }
      }
      let timestampend = new Date().getTime();
      let totalNum = Number(descMountNum[0] * 60) + Number(descMountNum[1].replace(/[^\d]/g, ""));
      log("还要等待" + totalNum + " 秒" + (timestampend - timestampstart) + "毫秒");
      sleep((totalNum - 10) * 1000 - (timestampend - timestampstart));
      log("======等待结束,开始查找==========");
    } else if (/秒/.test(is_time)) {
      let testStr = is_time.replace(/[^\d]/g, "");
      log("等待:" + testStr + "秒");
      if (testStr > 10) {
        sleep(testStr * 1000 - 10000);
      }
    }
    return true;
  }

  function findRedPacket() {
    let widgetOneRedPacket = "";
    console.info("开始查询红包按键---");
    console.time("查询红包用时");
    widgetOneRedPacket = className("android.widget.Button").descStartsWith("红包").visibleToUser().findOne(5000);
    console.timeEnd("查询红包用时");
    console.verbose("当前第：" + 查询红包次数++ + " 次查询红包");
    if (widgetOneRedPacket && widgetOneRedPacket.desc() == "红包") {
      widgetOneRedPacket.click();
      console.info("点击直播抢红包的位置");
      sleep(500);
      click(width2, height2);
      查询结果();
      log("抢完,等待关闭弹框");
    } else if (widgetOneRedPacket && widgetOneRedPacket.desc() != "红包") {
      if (timesplit(widgetOneRedPacket)) {
        if (!widgetOneRedPacket.click()) {
          clickCenter(widgetOneRedPacket);
          sleep(300);
          if (!widgetOneRedPacket.click()) {
            return log("点击失败，直播可能结束");
          }
        }
        log("等待结束 开始查询和校验抢红包控件 ");
        let 循环 = true;
        let 倒计时退出 = threads.start(function () {
          sleep(13000);
          log("等待时间到退出查询抢红包~~~");
          循环 = false;
        });
        while (循环) {
          let 抢红包按键 = boundsInside(bounds1, bounds2, bounds3, bounds4).clickable().visibleToUser().findOnce();
          if (抢红包按键) {
            if (!抢红包按键.click()) {
              clickCenter(抢红包按键);
              log("控件点击失败，位置点击");
            }
            let 控件大小 = 抢红包按键.bounds().bottom - 抢红包按键.bounds().top;
            log(控件大小);
            if (控件大小 < 250) {
              continue;
            }
            查询结果();
            log("抢红包按键已点击完成退出查询");
            break;
          }
        }
        倒计时退出.interrupt();
      } else {
        return log("等待超设定时间，不等待执行抢红包");
      }
    } else {
      back();
      console.info("没找到红包,切换直播房间");
    }
    //重新给全局设置为0  当超过5次退出直播房间
    if (widgetOneRedPacket) {
      findRedPacket();
    }
  }

  //==================================通用方法===============

  /**
   * 根据内容获取一个对象S
   *
   * @param {string} contentVal
   * @param {number} timeout 默认超时时间5秒
   * @param {boolean} containType 是否带回类型
   * @param {boolean} suspendWarning 是否隐藏warning信息
   * @param {function} appendFilter 附加查询条件 详见UiSelector
   */
  function widgetGetOne(contentVal, timeout, containType, suspendWarning, appendFilter, options) {
    let target = null;
    let isDesc = false;
    let waitTime = timeout || 5000;
    let timeoutFlag = true;
    log("try to find one: %s timeout: %s ms", contentVal.toString(), waitTime);
    let checkResult = widgetCheck(contentVal, waitTime, true, appendFilter, options);
    if (!checkResult.timeout) {
      timeoutFlag = false;
      target = checkResult.target;
      isDesc = checkResult.isDesc;
    }
    // 当需要带回类型时返回对象 传递target以及是否是desc
    if (target && containType) {
      let result = {
        target: target,
        bounds: target.bounds(),
        isDesc: isDesc,
        content: isDesc ? target.desc() : target.text(),
      };
      return result;
    }
    return target;
  }

  /**
   * 替换控件搜索算法DFS,BFS,VDFS,VBFS,PDFS,PBFS,PVDFS,PVBFS
   * DFS,BFS为默认提供的深度优先和广度优先搜索算法
   * VDFS,VBFS为我修改的只搜索可见控件（控件包括父级不可见则直接跳过）深度优先和广度优先搜索算法 缺点是无法搜索不可见控件，适合一个界面中有巨量控件的时候用于加快搜索速度 实际数据抖音极速版从25s缩短到3s
   * PDFS,PBFS,PVDFS,PVBFS 是通过多线程搜索控件 大大加快搜索速度
   *
   * @param {string} algorithm 搜索算法DFS,BFS,VDFS,VBFS,PDFS,PBFS,PVDFS,PVBFS
   * @param {UiSelector} mselector
   * @return
   */
  function wrapSelector(algorithm, appendFilter, mselector) {
    appendFilter =
      appendFilter ||
      function (matcher) {
        return matcher;
      };
    mselector = appendFilter(mselector || selector());
    if (!algorithm) {
      return mselector;
    }
    current = this.getCurrentAlgorithm();
    if (current == algorithm) {
      return mselector;
    }
    console.verbose("替换搜索算法为：" + algorithm + " 原始算法：" + current);
    return AlgorithmChanger.changeAlgorithm(mselector, algorithm);
  }

  /**
   * 校验控件是否存在
   * @param {String} contentVal 控件文本
   * @param {Number} timeoutSetting 超时时间 单位毫秒
   * @param {Boolean} containType 返回结果附带文本是desc还是text
   * @param {Object} options 额外参数
   * 超时返回false
   */
  function widgetCheck(contentVal, timeoutSetting, containType, appendFilter, options) {
    options = options || {};
    let timeout = timeoutSetting || 5000;
    let timeoutFlag = true;
    let countDown = new java.util.concurrent.CountDownLatch(1);
    let matchRegex = new RegExp(contentVal);
    let isDesc = false;
    let target = null;
    let descThread = threads.start(function () {
      target = wrapSelector(options.algorithm, appendFilter).descMatches(matchRegex).findOne();
      let res = target.desc();
      log("find desc " + contentVal + " " + res);
      timeoutFlag = false;
      isDesc = true;
      countDown.countDown();
    });

    let textThread = threads.start(function () {
      target = wrapSelector(options.algorithm, appendFilter).textMatches(matchRegex).findOne();
      let res = target.text();
      log("find text " + contentVal + "  " + res);
      timeoutFlag = false;
      countDown.countDown();
    });

    let timeoutThread = threads.start(function () {
      sleep(timeout);
      countDown.countDown();
    });
    countDown.await();
    descThread.interrupt();
    textThread.interrupt();
    timeoutThread.interrupt();
    if (timeoutFlag) {
      log("cannot find any matches " + contentVal + " timeout:" + timeout);
    }
    if (containType) {
      log("查询目标:" + contentVal);
      return {
        timeout: timeoutFlag,
        target: target,
        bounds: target ? target.bounds() : null,
        isDesc: isDesc,
      };
    }
    return !timeoutFlag;
  }

  function clickCenter(obj, x, y) {
    x = x || 0;
    y = y || 0;
    if (obj.bounds().centerX() > width || obj.bounds().centerY() > height || obj.bounds().centerX() < 0 || obj.bounds().centerY() < 0) {
      return log("不可点击范围:" + obj.bounds().centerX() + " " + obj.bounds().centerY() + " 额外" + x + "," + y);
    }
    click(Number(obj.bounds().centerX() + x), Number(obj.bounds().centerY() + y));
    log(obj.text() + " 点击位置：" + Number(obj.bounds().centerX() + x) + " " + Number(obj.bounds().centerY() + y));
  }

  /**
   * 找到并且点击 如果返回错误就点击中心 返回一个布尔值
   * @param {str} 要找的字符串
   */
  function findAndClick(str, sleepTime) {
    sleepTime = sleepTime || 5000;
    let widgetGet = widgetGetOne(str, sleepTime);
    if (widgetGet) {
      if (widgetGet.clickable && widgetGet.click()) {
        console.info("找到了:" + str + " 控件点击");
      } else if (widgetGet.parent().clickable && widgetGet.parent().click()) {
        console.info("找到了:" + str + " 控件点击父类");
      } else if (widgetGet.parent().parent().clickable && widgetGet.parent().parent().click()) {
        console.info("找到了:" + str + " 控件点击父类的父类");
      } else {
        clickCenter(widgetGet);
      }
      sleep(1000);
      return widgetGet;
    }
    return false;
  }

  // 杀死后台
  function killApp(appName) {
    //填写包名或app名称都可以
    const name = getPackageName(appName); //通过app名称获取包名
    app.openAppSetting(name); //通过包名打开应用的详情页(设置页)
    findAndClick(/强.*|停.*|结.*/);
    findAndClick(/强.*|停.*|结.*/);
    findAndClick(/确定/);
    home();
    sleep(1000);
  }

  //=============================

  function 抖音复制上面评价() {
    try {
      let 说的内容 = http.get("https://v1.hitokoto.cn").body.json().hitokoto.substring(0, 49);
      log(说的内容);
      if (说的内容) {
        if (说的内容) {
          setClip(说的内容);
        } else {
          setClip("点赞提高抢红包概率~~~");
        }
        findAndClick("说点什么.*");
        sleep(1000);
        input(说的内容);
        // paste();
        findAndClick("发送");
      }
    } catch (e) {
      log("网络请求错误,随机名言失败");
    }
  }

  function 抖音互粉互赞() {
    sleep(1000);
    setClip(互粉互赞[Math.floor(Math.random() * 互粉互赞.length - 1)]);
    findAndClick("说点什么.*");
    sleep(1000);
    paste();
    findAndClick("发送");
  }

  function 抖音给主播点赞() {
    let 更多面板 = widgetGetOne("红包.*");
    if (更多面板) {
      let x = 更多面板.bounds().centerX();
      let y = 更多面板.bounds().centerY() + 100;
      let num = random(10, 20);
      log("点赞" + num);
      while (num > 0) {
        click(x, y);
        press(x, y, random(100, 150));
        num--;
      }
      sleep(1000);
      click(x, y);
    }
  }
  function 到指定房间打赏() {
    app.startActivity({
      data: "snssdk2329://live?room_id=7298324868583115535&user_id=66347639813&u_code=i8fg49bjkll&from=webview&refer=web",
    });
    let username2 = className("android.widget.TextView")
      .id(appid + ":id/user_name")
      .findOne(8000);
    if (username2) {
      toastLog("到达指定房间：" + username2.text());
    } else {
      toastLog("没到达指定房间退出");
      exit();
    }

    if (!findAndClick("背包")) {
      swipe(900, 1600, 400, 1600, 300);
      sleep(1000);
      swipe(900, 1600, 400, 1600, 300);
      sleep(1000);
      swipe(900, 1600, 400, 1600, 300);
      sleep(1000);
    }
    let 礼物数量 = findAndClick("x.|x..");
    if (礼物数量) {
      let 数量 = 礼物数量.text().replace("x", "");
      log("查询到礼物：" + 数量);
      let 点击位置 = widgetGetOne("赠送");
      for (var i = 0; i < 数量; i++) {
        clickCenter(点击位置);
        sleep(400);
      }
    }
    toastLog("任务结束");
    exit();
  }
  function 查询结果() {
    console.verbose("================================");
    sleep(2000);
    let 抢的结果 = widgetGetOne("与.*|已抢到.*|.*抖币.*|红包已.*|.钻已放.*");
    if (抢的结果) {
      console.info(抢的结果.text());
      if (/已/.test(抢的结果.text())) {
        console.info("在:" + username + " |抢到:" + 抢的结果.text());
        if (/抖币/.test(抢的结果.text()) || /钻已放/.test(抢的结果.text())) {
          let 抢到的抖币数量 = Number(抢的结果.text().replace(/[^\d]/g, ""));
          抢到红包统计 = 抢到红包统计 + 抢到的抖币数量;
          console.info("本次运行已抢：" + 抢到红包统计 + "抖币");
        }
        if (/啤酒/.test(抢的结果.text())) {
          console.info("本次运行已抢：" + ++抢到啤酒统计 + "啤酒");
        }
        if (/小心/.test(抢的结果.text())) {
          console.info("本次运行已抢：" + ++抢到小爱心统计 + "小爱心");
        }
        if (/小皇冠/.test(抢的结果.text())) {
          console.info("本次运行已抢：" + ++抢到小皇冠统计 + "小皇冠");
        }
        if (/棒棒糖/.test(抢的结果.text())) {
          console.info("本次运行已抢：" + ++抢到棒棒糖统计 + "棒棒糖");
        }
        if (/撩一下/.test(抢的结果.text())) {
          console.info("本次运行已抢：" + ++抢到撩一下统计 + "撩一下");
        }
        没抢到红包次数 = 0;
        back();
        sleep(1000);
      } else {
        没抢到红包次数++;
        console.verbose("第：" + 没抢到红包次数 + " 次没抢到红包");
        back();
        sleep(1000);
        if (没抢到红包次数 == 10) {
          console.info("连续10次查询都没抢到红包退出当前房间");
          widgetOneRedPacket = false;
        }
        if (没抢到红包次数 >= 20) {
          toastLog("连续20次没抢到红包，退出");
          home();
          exit();
        }
      }
    } else {
      back();
      console.error("查询结果超时,是不是app更新了，请确认一下版本号");
    }
  }

  function 找字(str, region, regex) {
    if (运行环境haimbot) {
      var res = ocr.recognize(captureScreen());

      for (var i = 0; i < res.results.length; i++) {
        let v = res.results[i];
        log(v.bounds + "  " + v.text);
        if (str.test(v.text)) {
          log("点击位置" + (v.bounds.left + v.bounds.right) / 2 + " " + (v.bounds.top + v.bounds.bottom) / 2);
          click((v.bounds.left + v.bounds.right) / 2, (v.bounds.top + v.bounds.bottom) / 2);
          return true;
        }
      }
      return false;
    }

    region = region || [];
    log("截图找字：" + str);
    var 图片 = captureScreen();
    var recognizeText = qq.recognizeWithBounds(图片, region, regex);
    图片.recycle();
    log("文字查询结果：" + recognizeText.length);
    for (var i = 0; i < recognizeText.length; i++) {
      let v = recognizeText[i];
      log(v.bounds + "  " + v.label);
      if (str.test(v.label)) {
        log("点击位置" + (v.bounds.left + v.bounds.right) / 2 + " " + (v.bounds.top + v.bounds.bottom) / 2);
        click((v.bounds.left + v.bounds.right) / 2, (v.bounds.top + v.bounds.bottom) / 2);
        return true;
      }
    }
  }
}
